async function decryptEvent(encryptKey: string, encryptedEventBase64: string) {
	const keyData = new TextEncoder().encode(encryptKey);
	const keyHash = await crypto.subtle.digest('SHA-256', keyData);

	const key = await crypto.subtle.importKey('raw', keyHash, { name: 'AES-CBC' }, false, ['decrypt']);

	const encryptedEventBytes = base64ToArrayBuffer(encryptedEventBase64);
	const iv = encryptedEventBytes.slice(0, 16);
	const encryptedEvent = encryptedEventBytes.slice(16);

	const decryptedData = await crypto.subtle.decrypt(
		{
			name: 'AES-CBC',
			iv: iv,
		},
		key,
		encryptedEvent
	);

	const decryptedText = new TextDecoder().decode(decryptedData);
	return decryptedText;
}

function base64ToArrayBuffer(base64: string) {
	const binaryString = atob(base64);
	const len = binaryString.length;
	const bytes = new Uint8Array(len);
	for (let i = 0; i < len; i++) {
		bytes[i] = binaryString.charCodeAt(i);
	}
	return bytes.buffer;
}

// 将 ArrayBuffer 转为 base64 编码
function bufferToBase64(buffer) {
	const bytes = new Uint8Array(buffer);
	let binary = '';
	for (let i = 0; i < bytes.byteLength; i++) {
		binary += String.fromCharCode(bytes[i]);
	}
	return btoa(binary);
}

export { decryptEvent, bufferToBase64 };
